// Own header
#include "readingvaluemodel.h"

// Qt includes
#include <QDebug>

// Qt Mobility includes
#include <QSensorReading>


/*!
  \class ReadingValueModel
  \brief Contains the reading values of a sensor.
*/


/*!
  Constructor.
*/
ReadingValueModel::ReadingValueModel(QObject *parent) :
    QAbstractListModel(parent),
    m_sensor(0),
    m_cachedRowCount(0)
{
    QHash<int, QByteArray> roles;
    roles[ValueRole] = "value";
    setRoleNames(roles);
}


/*!
  Destructor.
*/
ReadingValueModel::~ReadingValueModel()
{
}


/*!
  From QAbstractListModel.
*/
QVariant ReadingValueModel::data(const QModelIndex &index,
                                 int role /* = Qt::DisplayRole */) const
{
    const int itemIndex(index.row());
    QSensorReading *reading(0);

    if (m_sensor) {
        reading = m_sensor->reading();
    }

    if (!reading || !index.isValid() || itemIndex >= reading->valueCount()) {
        // Failed to get a reading or the index is invalid!
        return QVariant();
    }

    if (role == ValueRole) {
        return reading->value(itemIndex);
    }

    return QVariant();
}


/*!
  From QAbstractListModel.
*/
int ReadingValueModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);

    if (m_sensor) {
        QSensorReading *reading = m_sensor->reading();

        if (reading) {
            return reading->valueCount();
        }
    }

    return 0;
}


/*!
  Sets the sensor.
*/
bool ReadingValueModel::setSensor(QSensor *sensor)
{
    if (m_sensor) {
        // Disconnect the old sensor.
        disconnect(m_sensor, SIGNAL(readingChanged()), this, SLOT(update()));
        beginResetModel();
        m_sensor = 0;
        endResetModel();
    }

    m_sensor = sensor;

    if (m_sensor) {
        if (!m_sensor->isActive()) {
            // Start the sensor.
            qDebug() << "Starting the sensor.";
            bool success = m_sensor->start();

            if (success) {
                qDebug() << "Sensor started successfully!";
            }
            else {
                qDebug() << "Failed to start the sensor!";
                m_cachedRowCount = 0;
                m_sensor = 0;
                return false;
            }
        }

        m_cachedRowCount = rowCount();

        beginInsertRows(QModelIndex(), 0, m_cachedRowCount - 1);
        endInsertRows();

        // Connect the signals.
        connect(m_sensor, SIGNAL(readingChanged()), this, SLOT(update()),
                Qt::UniqueConnection);
    }

    emit rowCountChanged(rowCount());
    return true;
}


/*!
  Notifies about changed values.
*/
void ReadingValueModel::update()
{
    QModelIndex topLeft = createIndex(0, 0);
    QModelIndex bottomRight = createIndex(m_cachedRowCount, 0);
    emit dataChanged(topLeft, bottomRight);
}


// End of file.
